/**
 * @file main.c
 * @author Ai-Thinker
 * @brief st7789 显示屏显示测试
 * @version 0.1
 * @date 2021-10-11
 *
 * @copyright Copyright (c) 2021
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"

#include "lvgl.h"
#include "lvgl_helpers.h"

SemaphoreHandle_t xGuiSemaphore;
void app_main(void)
{
    xGuiSemaphore = xSemaphoreCreateMutex();
    lv_init();
    lvgl_driver_init();

    lv_color_t* buf1 = heap_caps_malloc(DISP_BUF_SIZE * sizeof(lv_color_t), MALLOC_CAP_DMA);
    assert(buf1 != NULL);
    lv_color_t* buf2 = heap_caps_malloc(DISP_BUF_SIZE * sizeof(lv_color_t), MALLOC_CAP_DMA);
    assert(buf2 != NULL);
    static lv_disp_buf_t disp_buf;
    uint32_t size_in_px = DISP_BUF_SIZE;

    lv_disp_buf_init(&disp_buf, buf1, buf2, size_in_px);

    lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.flush_cb = disp_driver_flush;

#ifdef CONFIG_LV_TFT_DISPLAY_MONOCHROME
    disp_drv.rounder_cb = disp_driver_rounder;
    disp_drv.set_px_cb = disp_driver_set_px;
#endif
    disp_drv.draw_buf = &disp_buf;
    lv_disp_drv_register(&disp_drv);

    lv_obj_t* scr = lv_disp_get_scr_act(NULL);
    //创建标签
    lv_obj_t* label1 = lv_label_create(scr, NULL);

    lv_label_set_text(label1, "Hello world!");//设置标签内容
    lv_obj_set_style_local_text_color(label1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLUE);//设置内容颜色
    lv_obj_set_style_local_text_font(label1, LV_LABEL_PART_MAIN, LV_STATE_EDITED, LV_FONT_MONTSERRAT_10);
    lv_obj_align(label1, NULL, LV_ALIGN_IN_BOTTOM_MID, 0, 0);//显示
    //创建文本框
    lv_obj_t* textarea1 = lv_textarea_create(scr, NULL);
    for (size_t i = 0; i < 10; i++)
        lv_textarea_del_char_forward(textarea1);

    lv_textarea_add_text(textarea1, "TEXTTAREA");

    lv_obj_set_height(textarea1, 40);
    lv_obj_set_width(textarea1, 165);
    lv_obj_set_style_local_bg_color(textarea1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_CYAN);
    lv_obj_set_style_local_text_color(textarea1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLUE);
    lv_obj_align(textarea1, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 0);

    lv_obj_t* lv_win1 = lv_win_create(scr, NULL);
    lv_obj_set_height(lv_win1, 150);
    lv_obj_set_width(lv_win1, 150);
    lv_obj_set_style_local_bg_color(lv_win1, LV_LABEL_PART_MAIN, LV_STATE_EDITED, LV_COLOR_BLUE);
    lv_obj_align(lv_win1, NULL, LV_ALIGN_CENTER, 0, 0);


    while (1) {
        /* Delay 1 tick (assumes FreeRTOS tick is 10ms */
        vTaskDelay(pdMS_TO_TICKS(10));

        /* Try to take the semaphore, call lvgl related function on success */
        if (pdTRUE == xSemaphoreTake(xGuiSemaphore, portMAX_DELAY)) {
            lv_task_handler();
            xSemaphoreGive(xGuiSemaphore);
        }
    }
    free(buf1);
}
